package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

// ConfigManager 管理应用配置
type ConfigManager struct {
	appList     []AppListItem
	datasetList []DatasetItem
}

// LoadEnvFile 从 .env 文件加载环境变量
func LoadEnvFile(filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		// 跳过空行和注释
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		// 解析 KEY=VALUE 格式
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key := strings.TrimSpace(parts[0])
		value := strings.TrimSpace(parts[1])

		// 只有当环境变量未设置时才设置
		if os.Getenv(key) == "" {
			os.Setenv(key, value)
		}
	}

	return scanner.Err()
}

// AppConfig 应用配置结构
type AppConfig struct {
	App struct {
		Port         string `yaml:"port" json:"port"`
		ExternalPort string `yaml:"external_port" json:"external_port"`
		ApiPrefix    string `yaml:"api_prefix" json:"api_prefix"`
	} `yaml:"app" json:"app"`
	Docker struct {
		ImageName string `yaml:"image_name" json:"image_name"`
		Version   string `yaml:"version" json:"version"`
		Namespace string `yaml:"namespace" json:"namespace"`
		Registry  string `yaml:"registry" json:"registry"`
	} `yaml:"docker" json:"docker"`
}

// LoadConfig 从环境变量加载配置
func LoadConfig() (*AppConfig, error) {
	// 尝试加载 .env 文件
	_ = LoadEnvFile(".env")

	// 默认配置
	config := &AppConfig{}
	config.App.Port = "8000"
	config.App.ExternalPort = "8000"
	config.App.ApiPrefix = "/api/v1"
	config.Docker.ImageName = "hub-modules-2-modelhubapi2"
	config.Docker.Version = "latest"
	config.Docker.Namespace = "default"

	// 从环境变量加载配置
	if port := os.Getenv("PORT"); port != "" {
		config.App.Port = port
	}
	if externalPort := os.Getenv("EXTERNAL_PORT"); externalPort != "" {
		config.App.ExternalPort = externalPort
	}
	if apiPrefix := os.Getenv("API_PREFIX"); apiPrefix != "" {
		config.App.ApiPrefix = apiPrefix
	}
	if imageName := os.Getenv("IMAGE_NAME"); imageName != "" {
		config.Docker.ImageName = imageName
	}
	if version := os.Getenv("VERSION"); version != "" {
		config.Docker.Version = version
	}
	if namespace := os.Getenv("NAMESPACE"); namespace != "" {
		config.Docker.Namespace = namespace
	}
	if registry := os.Getenv("DOCKER_REGISTRY"); registry != "" {
		config.Docker.Registry = registry
	}

	fmt.Printf("Configuration loaded from environment variables:\n")
	fmt.Printf("  PORT: %s\n", config.App.Port)
	fmt.Printf("  EXTERNAL_PORT: %s\n", config.App.ExternalPort)
	fmt.Printf("  API_PREFIX: %s\n", config.App.ApiPrefix)
	fmt.Printf("  IMAGE_NAME: %s\n", config.Docker.ImageName)
	fmt.Printf("  VERSION: %s\n", config.Docker.Version)
	fmt.Printf("  NAMESPACE: %s\n", config.Docker.Namespace)
	fmt.Printf("  DOCKER_REGISTRY: %s\n", config.Docker.Registry)

	return config, nil
}

// NewConfigManager 创建一个新的配置管理器
func NewConfigManager() (*ConfigManager, error) {
	cm := &ConfigManager{}

	// 读取 appList.json
	if err := cm.loadAppList(); err != nil {
		return nil, err
	}

	// 读取 datasets.json
	if err := cm.loadDatasetList(); err != nil {
		return nil, err
	}

	return cm, nil
}

// loadAppList 加载应用列表
func (cm *ConfigManager) loadAppList() error {
	filePath := GetConfigPath()
	fmt.Printf("Loading config from: %s\n", filePath)

	data, err := os.ReadFile(filePath)
	if err != nil {
		return fmt.Errorf("failed to read appList.json from %s: %v", filePath, err)
	}

	if err := json.Unmarshal(data, &cm.appList); err != nil {
		return fmt.Errorf("failed to parse appList.json: %v", err)
	}

	return nil
}

// loadDatasetList 加载数据集列表
func (cm *ConfigManager) loadDatasetList() error {
	filePath := GetDatasetConfigPath()
	fmt.Printf("Loading datasets from: %s\n", filePath)

	data, err := os.ReadFile(filePath)
	if err != nil {
		return fmt.Errorf("failed to read datasets.json from %s: %v", filePath, err)
	}

	if err := json.Unmarshal(data, &cm.datasetList); err != nil {
		return fmt.Errorf("failed to parse datasets.json: %v", err)
	}

	return nil
}

// GetAppConfig 获取应用配置
func (cm *ConfigManager) GetAppConfig(namespace, name, configType string) (*AppListItem, bool) {
	for _, app := range cm.appList {
		if app.Namespace == namespace && app.Name == name {
			return &app, true
		}
	}
	return nil, false
}

// GetAllModels 获取所有模型
func (cm *ConfigManager) GetAllModels() []AppListItem {
	return cm.appList
}

// GetModel 获取特定模型
func (cm *ConfigManager) GetModel(namespace, name string) (*AppListItem, bool) {
	for _, model := range cm.appList {
		if model.Namespace == namespace && model.Name == name {
			return &model, true
		}
	}
	return nil, false
}

// GetAllDatasets 获取所有数据集
func (cm *ConfigManager) GetAllDatasets() []DatasetItem {
	return cm.datasetList
}

// GetDataset 获取特定数据集
func (cm *ConfigManager) GetDataset(namespace, name string) (*DatasetItem, bool) {
	for _, dataset := range cm.datasetList {
		if dataset.Namespace == namespace && dataset.Name == name {
			return &dataset, true
		}
	}
	return nil, false
}
